
class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :get_related_products]
  layout "product"

  def index
    @root_categories = Category.roots

    basic_query = Product.search(search_params).page(params[:page] || 1)
    @products = basic_query.records
  end

  def show
    @promotions = @product.get_promotions
    @related = Product.get_related_products(@product.id, @product.category_ids)
    @product_images = @product.images.limit(4)

    set_seo_meta(
      "【#{@product.brand_title}】 " + @product.title,
      @product.summary,
      nil
    )
    log_viewed
  end

  def get_related_products
    @related = Product.get_related_products(@product.id, @product.category_ids)
    render_success('成功获取关联商品', data: @related)
  end

  private

  def log_viewed
  end

  def search_params
    {
      sort: get_sort(),
      query: {
        bool: {
          must: get_matches(),
          filter: get_filters()
        }
      },
      highlight: {
        pre_tags: ["[h]"],
        post_tags: ["[/h]"],
        fields: { title: {}, desc: {} }
      }
    }
  end

  def get_filters
    filters = []
    if params[:brand_id]
      filters << { term: { brand_id: params[:brand_id] } }
    end
    if params[:category_id]
      filters << { term: { category_ids: params[:category_id] } }
    end
    filters
  end

  def get_matches
    if params[:q].blank?
      {
        match_all: {}
      }
    else
      {
        multi_match: {
          query: get_q(),
          fields: [
            :title, :desc
          ]
        }
      }
    end
  end

  def get_sort
    sort = [{ id: { order: "desc"} }]

    if params[:sort] =~ /\A\w+-\w+$/
      sort_str = params[:sort].split(/-/)
      sort.pop
      sort << { sort_str[0] => { order: sort_str[1] } }
    end
    sort
  end

  def get_q
    params[:q] || ""
  end

  def get_sort_params
    sorts = {id: "desc"}
    if params[:sort] =~ /\A\w+-\w+$/
      sort_str = params[:sort].split(/-/)
      { sort_str[0] => sort_str[1] }.merge!(sorts)
    else
      sorts
    end
  end

  def set_product
    @product = Product.find(params[:id])
  end
end
